package com.weilive.platform.third;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.weilive.core.netty.http.HttpServletManager;
import com.weilive.core.utils.ClassUtils;
import com.weilive.platform.cache.app.AppManager;
import com.weilive.platform.cache.app.AppObj;
import com.weilive.platform.dao.app.mapper.AppChannelDO;
import com.weilive.platform.third.ThirdPlatSDK.ThirdCheck;

public class ThirdSDKManager {

	private static final Logger log = LoggerFactory.getLogger(ThirdSDKManager.class);
	private static final HashMap<String, Class<?>> platSDKClasses = new HashMap<String, Class<?>>();
	private static final HashMap<String, ThirdPlatSDK> platSDKs = new HashMap<String, ThirdPlatSDK>();

	public static void loadBySpring(ApplicationContext context) {
		reloadData();
	}

	public static void reloadData() {
		platSDKClasses.clear();
		for (Class<?> c : ClassUtils.getClassList(ThirdPlatSDK.class.getPackage().getName(), true,
				ThirdPlatSDK.class)) {
			platSDKClasses.put(c.getSimpleName(), c);
			log.info("===> load third sdk: " + c.getSimpleName());
		}
		// TODO
		// Class c1 = Plat91SDK.class;
		// platSDKClasses.put(c1.getSimpleName(), c1);
		platSDKs.clear();
		for (AppObj app : AppManager.getAllApp()) {
			for (AppChannelDO channel : app.getChannels()) {
				Class<?> c = platSDKClasses.get(channel.sdk_name);
				if (c != null) {
					try {
						ThirdPlatSDK sdk = (ThirdPlatSDK) c.newInstance();
						sdk.setChannelInfo(channel);
						platSDKs.put(channel.channel + channel.app_id, sdk);
						HttpServletManager.registerServlet(
								sdk.createPayNotifyServlet("/pay/app" + channel.app_id + "/" + channel.channel));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static ThirdCheck checkUserLogin(int game_id, String channel, String uid, String token, String attach)
			throws Exception {
		ThirdPlatSDK sdk = platSDKs.get(channel + game_id);
		return sdk != null ? sdk.checkUserLogin(uid, token, attach) : null;
	}

	public static int verifyOrder(int game_id, String pay_type, String order_cid, String receipt, String attach)
			throws Exception {
		ThirdPlatSDK paySDK = platSDKs.get(pay_type + game_id);
		return paySDK != null ? paySDK.verifyOrder(order_cid, receipt, attach) : ThirdConstants.PAY_NOT_SUPPORT;
	}
}
